package cn.nawang.ebeim.server.transfer;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

/**
 * Created by GanJc on 2016-01-04 08:56
 */
public class TransferAuthService {

    private static final Logger LOG = LoggerFactory.getLogger(TransferAuthService.class);

    /**
     * 程序中的URL能涉及到的字符
     */
    private static String URL_STRINGS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUUVWXYZ?=&!@#_.-";

    /**
     * 随机生成的用于存档的字符映射表
     * (存于数据库或文件,重置后,需同时更新服务端和客户端)
     */
    private static String SECRET_DIC = "{\"!\":\"9AWh\",\"#\":\"7m5C\",\"&\":\"dD1&\",\"-\":\"3feL\",\".\":\".ZYE\",\"0\":\"2zdt\",\"1\":\"Ntsw\",\"2\":\"ivMM\",\"3\":\"Dd&K\",\"4\":\".d8a\",\"5\":\"scTG\",\"6\":\"w?OT\",\"7\":\"VeiQ\",\"8\":\".GaM\",\"9\":\"1MEi\",\"=\":\"FSvZ\",\"?\":\"CrSv\",\"@\":\"w2so\",\"A\":\"JpW_\",\"B\":\"-hR?\",\"C\":\"yKE1\",\"D\":\"9.hz\",\"E\":\"?6L9\",\"F\":\"!#RC\",\"G\":\"HJru\",\"H\":\"mzxN\",\"I\":\"wCaj\",\"J\":\"pAMw\",\"K\":\"8@Gd\",\"L\":\"laDF\",\"M\":\"?g5j\",\"N\":\"HXzt\",\"O\":\"BPTm\",\"P\":\"Zxtm\",\"Q\":\"WmXi\",\"R\":\"SOZn\",\"S\":\"3jYb\",\"T\":\"EidD\",\"U\":\"MNld\",\"V\":\"eLe3\",\"W\":\"0#&s\",\"X\":\"9d??\",\"Y\":\"oSPU\",\"Z\":\"Sbso\",\"_\":\"lCUg\",\"a\":\"DRis\",\"b\":\"u1pw\",\"c\":\"VgDE\",\"d\":\"KW12\",\"e\":\"cuM7\",\"f\":\"9Oit\",\"g\":\"MqEV\",\"h\":\"pPA&\",\"i\":\"S_GF\",\"j\":\"yZTh\",\"k\":\"ZZig\",\"l\":\"URY0\",\"m\":\"kM7P\",\"n\":\"?!qd\",\"o\":\"@nY9\",\"p\":\"J#RM\",\"q\":\"c25H\",\"r\":\"fiey\",\"s\":\"ZO#u\",\"t\":\"Hd=M\",\"u\":\"41PR\",\"v\":\"Uyu=\",\"w\":\"cIP-\",\"x\":\"!ZvP\",\"y\":\"QFSC\",\"z\":\"qnbU\"}";

    /**
     * 用于加解密的字符映射表,SECRET_DIC的map版.
     */
    private static Map SECRET_MAP = new HashMap();

    static {
        SECRET_MAP = JSON.parseObject(SECRET_DIC,Map.class);
        LOG.info("SECRET_DIC：{}", SECRET_DIC);
        LOG.info("SECRET_MAP：{}", SECRET_MAP);
    }

    public static String encryptUrl(String url) {
        String[] strings = url.split("");
        StringBuffer sb = new StringBuffer(strings.length * 4);
        for (String s : strings) {
            sb.append(SECRET_MAP.get(s));
        }
        return sb.toString();
    }

    public static String decryptUrl(String url) {
        List<String> strings = splitUrl(url);
        StringBuffer sb = new StringBuffer();
        for (String s : strings) {
            for (Object key : SECRET_MAP.keySet()) {
                if (SECRET_MAP.get(key).equals(s)) {
                    sb.append(key);
                    break;
                }
            }
        }
        return sb.toString();
    }

    private static List<String> splitUrl(String url) {
        List<String> strings = new ArrayList<String>();
        int n = 4;
        String s;
        int t;
        int a = url.length() / n + 1;
        for (int i = 0; i < a; i++) {
            if (url.length() > 0) {
                t = url.length() > n ? n : url.length();
                s = url.substring(0, t);
                url = url.substring(t);
                strings.add(s);
            }
        }
        return strings;
    }

    public static void main(String[] args) {
        // 目前只生成一次,存于文件中颁发给客户端使用,所以先用指定时间种子，
        // 如需满足定时更换字典需求，只需把时间种子提取到配置文件即可
        Random random = new Random(47);
        String[] strings = URL_STRINGS.split("");
        for (String s : strings) {
            StringBuffer sb = new StringBuffer(4);
            sb.append(strings[random.nextInt(strings.length)])
                    .append(strings[random.nextInt(strings.length)])
                    .append(strings[random.nextInt(strings.length)])
                    .append(strings[random.nextInt(strings.length)]);
            String value = sb.toString();
            SECRET_MAP.put(s, value);
        }
        SECRET_DIC = JSON.toJSON(SECRET_MAP).toString();
        System.out.println(SECRET_DIC);
    }

}
